package com.elm.service.impl;

import com.elm.mapper.DeliveryAddressMapper;
import com.elm.mapper.UserMapper;
import com.elm.po.DeliveryAddress;
import com.elm.po.Food;
import com.elm.po.User;
import com.elm.service.DeliveryAddressService;
import com.elm.util.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class DeliveryAddressServiceImpl implements DeliveryAddressService {
    @Autowired
    private DeliveryAddressMapper addressMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private HttpServletRequest request;

    private String getCurrentUserType() {
		String token = (String) request.getAttribute("token");
		return JwtUtil.getUserTypeFromToken(token);
	}
    
    private String getCurrentUserName() {
        String token = (String) request.getAttribute("token");
        return JwtUtil.getUsernameFromToken(token);
    }

    @Override
    public List<DeliveryAddress> getDeliveryAddressByUserId(int userId) {
        // 验证地址所属权
        if (userId!=(userMapper.getUserIdByName(getCurrentUserName())) && !("ADMIN").equals(getCurrentUserType())) {
            throw new RuntimeException("权限不足：无权限查看他人地址");
        }
        return addressMapper.getDeliveryAddressByUserId(userId);
    }

    @Override
    public DeliveryAddress saveDeliveryAddress(DeliveryAddress deliveryAddress) {
        deliveryAddress.setUserId(userMapper.getUserIdByName(getCurrentUserName()));
     // 执行插入，insert会自动为cart的id字段赋值（自增ID）
        int rows = addressMapper.saveDeliveryAddress(deliveryAddress);
        if (rows <= 0) {
            throw new RuntimeException("错误：添加地址失败");
        }
        // 直接通过自增ID查询刚刚插入的记录
        int daid=deliveryAddress.getId();
        System.out.println(daid);
        return addressMapper.getDeliveryAddressById(daid);
    }

    @Override
    public DeliveryAddress getDeliveryAddressById(Integer daId) {
        DeliveryAddress address = addressMapper.getDeliveryAddressById(daId);
        if (address.getUserId()!=(userMapper.getUserIdByName(getCurrentUserName())) && !("ADMIN").equals(getCurrentUserType())) {
            throw new RuntimeException("权限不足：无权限查看他人地址");
        }
        return address;
    }

    @Override
    public DeliveryAddress updateDeliveryAddress(DeliveryAddress deliveryAddress) {
        DeliveryAddress oldAddress = addressMapper.getDeliveryAddressById(deliveryAddress.getId());
        if (oldAddress.getUserId()!=(userMapper.getUserIdByName(getCurrentUserName()))) {
            throw new RuntimeException("权限不足：无权限修改他人地址");
        }
        addressMapper.updateAddressStatus(deliveryAddress.getId());
        deliveryAddress.setId(null);
        deliveryAddress.setUserId(oldAddress.getUserId());
        int rows = addressMapper.saveDeliveryAddress(deliveryAddress);
        if (rows <= 0) {
            throw new RuntimeException("错误：添加地址失败");
        }
        // 直接通过自增ID查询刚刚插入的记录
        int daid=deliveryAddress.getId();
        return addressMapper.getDeliveryAddressById(daid);
    }

    @Override
    public int removeDeliveryAddress(Integer daId) {
        DeliveryAddress address = addressMapper.getDeliveryAddressById(daId);
        if (address.getUserId()!=(userMapper.getUserIdByName(getCurrentUserName()))) {
            throw new RuntimeException("权限不足：无权限删除他人地址");
        }
        return addressMapper.removeDeliveryAddress(daId);
    }

    @Override
    public DeliveryAddress setDefaultAddress(Integer daId) {
        DeliveryAddress address = addressMapper.getDeliveryAddressById(daId);
        if (address.getUserId()!=(userMapper.getUserIdByName(getCurrentUserName()))) {
            throw new RuntimeException("权限不足：无权限设置他人地址为默认");
        }
        addressMapper.resetUserDefaultAddress(userMapper.getUserIdByName(getCurrentUserName()));
        addressMapper.setDefaultAddress(daId);
        return addressMapper.getDeliveryAddressById(daId);
    }
}